﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using System.Windows.Navigation;
using ComicIsland.App.CIHelper;
using ComicIsland.App.Resources;
using ComicIsland.Common;
using ComicIsland.Common.Entities;
using ComicIsland.Common.Entities.InterfaceJson;
using ComicIsland.Common.Entities.LocalDatabase;
using ComicIsland.Common.Entities.LocalJson;
using ComicIsland.Common.WebHelper;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace ComicIsland.App.Views
{
    /// <summary>
    /// 漫画章节详情
    /// </summary>
    public partial class ComicDetailChapterPage : PhoneApplicationPage
    {
        private bool IsNeedReloadData = false;
        private int comicId = 0, bookId = 0;
        private string comicSource = string.Empty, comicCoverUrl = string.Empty, comicTitle = string.Empty;
        public ComicDetailChapterPage()
        {
            InitializeComponent();
            IsNeedReloadData = true;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string tmpComicId, tmpBookId;
            base.NavigationContext.QueryString.TryGetValue("comicId", out tmpComicId);
            int.TryParse(tmpComicId, out comicId);
            base.NavigationContext.QueryString.TryGetValue("bookId", out tmpBookId);
            int.TryParse(tmpBookId, out bookId);
            if (comicId <= 0 || bookId <= 0)
            {
                if (base.NavigationService.CanGoBack)
                {
                    base.NavigationService.GoBack();
                }
                return;
            }


            base.NavigationContext.QueryString.TryGetValue("comicSource", out comicSource);
            if (!string.IsNullOrWhiteSpace(comicSource))
                this.txtComicSource.Text = string.Format("来源站点：{0}", comicSource);
            else
                this.txtComicSource.Text = "默认站点";
            base.NavigationContext.QueryString.TryGetValue("comicCoverUrl", out comicCoverUrl);
            base.NavigationContext.QueryString.TryGetValue("comicTitle", out comicTitle);
            this.txtTitle.Text = comicTitle;

            if (this.IsNeedReloadData)
            {
                LoadComicChapter(comicId);
            }

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            this.IsNeedReloadData = true;
            base.OnNavigatedFrom(e);
        }

        private void pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.pivotDownloadedChapter == this.pivot.SelectedItem)
            {
                LoadDownloadChapter();
            }
        }

        void LoadDownloadChapter()
        {
            this.psbStatus.OpenStatusBar(AppResources.DataLoading);
            try
            {
                var items = App.dbContextHelper.GetAllChaptersByComicId(this.comicId, this.bookId);
                if (items != null && items.Count > 0)
                {
                    var itemssources = (from p in items where ContentDownloadStatus.已完成.ToString().Equals(p.DownloadStatus) select p).ToList<LDBComicChapter>();
                    if (itemssources != null && itemssources.Count > 0)
                    {
                        this.llsDownloaded.ItemsSource = new ObservableCollection<LDBComicChapter>(items);
                    }
                }
            }
            catch { }
            finally
            {
                this.psbStatus.CloseStatusBar();
            }
        }

        /// <summary>
        /// 加载漫画章节
        /// </summary>
        /// <param name="comicId"></param>
        public void LoadComicChapter(int comicId)
        {
            this.psbStatus.OpenStatusBar(AppResources.DataLoading);
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/downloadcomicsview_v3?bookid=", this.bookId.ToString(), "&", KEYS.REQUEST_QUERY_PLATFORM);
            //
            string cacheDataKey = string.Concat(KEYS.CacheJsonPrefix, MD5.GetMd5String(requestUrl));
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey);
            if (!cacheHelper.IsReload)
            {
                var rootCharacterString = JSONHelper.Deserialize<JsonComicChapter>(cacheHelper.LocalCacheData);
                if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.BookPartList != null && rootCharacterString.Info.BookPartList.Count > 0))
                {
                    //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                }
                else
                {
                    this.BindComicChapter(rootCharacterString.Info.BookPartList);
                }

                return;
            }

            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        if (result.IndexOf("\"info\":{}") >= 0)
                        {
                            LogHelper.LogError("未找到对应漫画！", this.GetType(), MethodBase.GetCurrentMethod());
                            return;
                        }
                        //
                        var rootCharacterString = JSONHelper.Deserialize<JsonComicChapter>(result);
                        if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.BookPartList != null && rootCharacterString.Info.BookPartList.Count > 0))
                        {
                            //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            cacheHelper.SetDataToLocalCache(cacheDataKey, result);
                            this.BindComicChapter(rootCharacterString.Info.BookPartList);
                        }

                        #endregion 获取结果处理
                    }
                    catch (Exception err)
                    {
                        this.psbStatus.CloseStatusBar();
                    }
                });
            }, webTask);
        }

        void BindComicChapter(ObservableCollection<JsonComicChapterInfoBookPartList> itemsource)
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                //if (itemsource != null && itemsource.Count > 0)
                //{
                //    foreach (JsonComicChapterInfoBookPartList item in itemsource)
                //    {
                //        if (item == null)
                //            continue;
                //        if (item.PartId <= 0)
                //            continue;
                //        bool isCached = App.dbContextHelper.IsCachedComicChapterByComicIdAndChapterId(this.comicId, item.PartId);
                //        item.IsCached = isCached;
                //        item.IsCachedToolTip = isCached ? "已下载" : "";
                //        item.IsCachedColor = isCached ? "#fff0f0f0" : "#ffffffff";
                //    }
                //}
                this.longListSelector.ItemsSource = itemsource;
                this.psbStatus.CloseStatusBar();
            });
        }

        /// <summary>
        /// 当前阅读章节
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnComicChapter_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var item = (sender as Button).DataContext as JsonComicChapterInfoBookPartList;
            if (item == null)
            {
                return;
            }
            string param = string.Concat("?comicId=", this.comicId, "&bookId=", this.bookId, "&comicPartId=", item.PartId, "&comicTitle=", Uri.EscapeDataString(this.comicTitle), "&comicPartTitle=", Uri.EscapeDataString(item.Name));
            Task.Run(() =>
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    this.AddOrUpdateBookcase(item.PartId, item.Name);
                });
            });
            NaviService.Navigate(ComicIslandPage.RCComicReaderPage, param);
        }

        /// <summary>
        /// 已下载章节
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDownloadedChapter_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var item = (sender as Button).DataContext as LDBComicChapter;
            if (item == null)
            {
                return;
            }
            string param = string.Concat("?comicId=", this.comicId, "&bookId=", this.bookId, "&comicPartId=", item.PartId, "&comicTitle=", Uri.EscapeDataString(this.comicTitle), "&comicPartTitle=", Uri.EscapeDataString(item.Name));
            Task.Run(() =>
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    this.AddOrUpdateBookcase(item.PartId, item.Name);
                });
            });
            NaviService.Navigate(ComicIslandPage.RCComicReaderPage, param);
        }

        /// <summary>
        /// 添加或更新收藏夹
        /// <para>添加时需要与服务器交互</para>
        /// </summary>
        /// <param name="partId"></param>
        /// <param name="partName"></param>
        void AddOrUpdateBookcase(int partId, string partName)
        {
            if (!(this.comicId > 0 && this.bookId > 0 && partId > 0))
            {
                return;
            }
            //收藏夹添加或更新
            LocalBookcaseInfoHelper helper = new LocalBookcaseInfoHelper();
            var bookcaseInfo = helper.Get(this.comicId);
            if (bookcaseInfo == null)
            {
                #region 添加
                bookcaseInfo = new LocalBookcaseInfo()
                {
                    ComicId = this.comicId,
                    ComicTitle = this.comicTitle,
                    Coverurl = this.comicCoverUrl,
                    BookId = this.bookId,
                    SourceName = this.comicSource,
                    PartId = partId,
                    PartName = partName,
                    IsSync = false,
                    Status = LocalBookcaseStatus.Add.ToString(),
                    LocalUpdateDate = DateTime.Now.ToString(KEYS.DATE_FORMAT_YMD)
                };

                if (bookcaseInfo.ComicId > 0 || bookcaseInfo.BookId > 0 && bookcaseInfo.PartId > 0)
                {
                    if (new LocalBookcaseInfoHelper().Add(bookcaseInfo))
                    {
                        //添加收藏则需要发往服务器
                        new WinPhoneDataUpdateHelper().SyncBookcaseInfo(KEYS.WpDataUpdateType.bookHandle, KEYS.WpDataUpdateTypeSyncBook.Add, bookcaseInfo);
                    }
                }
                #endregion 添加
            }
            else
            {
                #region 更新(无需同步)
                bookcaseInfo.BookId = this.bookId;
                bookcaseInfo.SourceName = this.comicSource;
                bookcaseInfo.PartId = partId;
                bookcaseInfo.PartName = partName;
                bookcaseInfo.IsSync = true;//更新（）
                bookcaseInfo.Status = LocalBookcaseStatus.Update.ToString();
                bookcaseInfo.LocalUpdateDate = DateTime.Now.ToString(KEYS.DATE_FORMAT_YMD);
                if (bookcaseInfo.ComicId > 0 || bookcaseInfo.BookId > 0 && bookcaseInfo.PartId > 0)
                {
                    if (new LocalBookcaseInfoHelper().Update(bookcaseInfo))
                    {
                        //更新就不处理了
                        //new WinPhoneDataUpdateHelper().SyncBookcaseInfo(KEYS.WpDataUpdateType.bookHandle, KEYS.WpDataUpdateTypeSyncBook.Add, bookcaseInfo);
                    }
                }
                #endregion 更新
            }
        }

        /// <summary>
        /// 默认是倒序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void appBarSort_Click(object sender, EventArgs e)
        {
            var appBarIcon = sender as ApplicationBarIconButton;
            if (appBarIcon != null)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    var items = this.longListSelector.ItemsSource as ObservableCollection<JsonComicChapterInfoBookPartList>;
                    if (appBarIcon.IconUri.ToString().EndsWith("AscendSort.png"))
                    {
                        appBarIcon.IconUri = new Uri("/Images/Icons/DescSort.png", UriKind.Relative);
                        this.longListSelector.ItemsSource = new ObservableCollection<JsonComicChapterInfoBookPartList>(items.OrderBy(p => p.PartId).ToList<JsonComicChapterInfoBookPartList>());
                    }
                    else
                    {
                        appBarIcon.IconUri = new Uri("/Images/Icons/AscendSort.png", UriKind.Relative);
                        this.longListSelector.ItemsSource = new ObservableCollection<JsonComicChapterInfoBookPartList>(items.OrderByDescending(p => p.PartId).ToList<JsonComicChapterInfoBookPartList>());
                    }
                });
            }
        }

        private void appBarCacheDownload_Click(object sender, EventArgs e)
        {
            if (this.comicId > 0 && this.bookId > 0)
            {
                string param = string.Concat("?comicId=", this.comicId, "&bookId=", this.bookId, "&comicSource=", Uri.EscapeDataString(this.comicSource),
                    "&comicCoverUrl=", Uri.EscapeDataString(this.comicCoverUrl), "&comicTitle=", Uri.EscapeDataString(this.comicTitle));
                //
                //NaviService.Navigate(ComicIslandPage.ComicDetailChapterDownloadQueuePage, param);
                //NaviService.Navigate(ComicIslandPage.CDComicChapterPage, param);
                NaviService.Navigate(ComicIslandPage.DCVSelectedDownloadComicChapterPage, param);
            }
        }

        private void longListSelector_ItemRealized(object sender, ItemRealizationEventArgs e)
        {
            if (e.ItemKind != LongListSelectorItemKind.Item)
                return;
            var container = e.Container;
            var currentSelectedItem = e.Container.Content as JsonComicChapterInfoBookPartList;
            if (currentSelectedItem == null)
                return;

            try
            {
                var items = Helper.FindChildren<Button>(container);
                if (!(items != null && items.Count() > 0))
                    return;

                foreach (Button item in items)
                {
                    if (item == null)
                        continue;
                    var row = App.dbContextHelper.GetOneComicChapter(this.comicId, this.bookId, currentSelectedItem.PartId);
                    if (row != null && ContentDownloadStatus.已完成.ToString().Equals(row.DownloadStatus))
                    {
                        item.Background = new SolidColorBrush(Helper.HexToColor(System.Convert.ToString(Application.Current.Resources["DefaultForegroundColor"])));
                        item.Foreground = new SolidColorBrush(Helper.HexToColor(System.Convert.ToString(Application.Current.Resources["DefaultBackgroundColor"])));
                    }
                    else
                    {
                        item.Background = new SolidColorBrush(Helper.HexToColor(System.Convert.ToString(Application.Current.Resources["DefaultBackgroundColor"])));
                        item.Foreground = new SolidColorBrush(Helper.HexToColor(System.Convert.ToString(Application.Current.Resources["DefaultForegroundColor"])));
                    }
                }

            }
            catch { }
        }









    }
}